package com.isoft.service.impl;

import com.isoft.entity.DfmeLbdeEntity;
import com.isoft.mapper.DfmeLbdeMapper;
import com.isoft.service.DfmeLbdeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeLbdeServiceImpl implements DfmeLbdeService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeLbdeServiceImpl.class);

    @Autowired
    private DfmeLbdeMapper dfmeLbdeMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-LBDE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeLbdeEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeLbdeEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeLbdeEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-LBDE XML structure");
            }

            processFlightData(entity);

            return "DFME-LBDE data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-LBDE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-LBDE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmeLbdeEntity entity) {
        // 插入元数据
        dfmeLbdeMapper.insertMeta(entity);

        // 尝试更新航班基础信息
        int updatedRows = dfmeLbdeMapper.updateFlightBase(entity);

        // 如果没有更新到任何行，则插入新记录
        if (updatedRows == 0) {
            dfmeLbdeMapper.insertFlightBase(entity);
        }

        // 插入登机完成时间
        if (entity.getDflt().getLastBaggageTime() != null && !entity.getDflt().getLastBaggageTime().isEmpty()) {
            dfmeLbdeMapper.insertBoardingTime(entity);
        }
    }
}